<template>
  <div
    class="fileSearch"
    @click="eStopPropagation($event)"
  >

    <div class="fileSearch-input">
      <vi-input-search
        placeholder="请输入文字进行文件名或全文搜索"
        style="width: 388px"
        @search="fileSearchFun"
        @change="searchChange($event)"
        :value="fileKeyWord"
      ></vi-input-search>
    </div>

    <div
      class="fileSearch-result"
      v-show="fileSearchVisible"
    >

      <div class="fileSearch-result-set">
        <vi-radio-group @change="searchTypeChange" v-model="searchType">
          <vi-radio :value="0">全部类别</vi-radio>
          <vi-radio :value="1">文件名</vi-radio>
          <vi-radio :value="2">正文</vi-radio>
        </vi-radio-group>

        <div class="fileSearch-result-set-info ell">
          共搜索到{{total}}条
        </div>

      </div>

      <div
        class="fileSearch-result-list"
        ref="resultDom"
        @scroll="resultDomScroll($event)"
      >
        <div
          class="fileSearch-result-list-none"
          v-if="fileListSearch.length===0"
        >
          暂无数据
        </div>

        <div
          v-for="file,index in fileListSearch"
          v-if="(fileListSearch.length!==0 && index >= ( (page-1)*size ) && index < ( page*size ) )||true"
          :key="file.id"
          class="fileSearch-result-list-item"
          :style="{padding: `${file.highlightText?'3px 10px':'8px 10px'}`,}"
          @click="fileIdClick(file.id, file.subFilePage)"
        >
          <div
            class="fileSearch-result-list-item-name ell"
            v-html="(file.highlightName && ( searchType == 1 || searchType == 0) )?file.highlightName:file.fileName"
          >
          </div>

          <div
            v-if="file.highlightText"
            class="fileSearch-result-list-item-text ell"
            v-html="file.highlightText"
          >
          </div>
        </div>

      </div>
    </div>

  </div>
</template>

<script>
import activeShowMixin from "../../mixin/activeShow.mixin";
import bus from '../../libs/event-bus'
import { baseURL } from "../../libs/http.js";

import _ from 'lodash';

export default {
  mixins: [activeShowMixin],
  data() {
    return {
      fileKeyWord: '', // 搜索关键词
      searchType: 0, // 0全部 1文件名 2正文
      page: 1,
      size: 10,
      total: 0,
    };
  },
  methods: {
    // 文件搜索
    fileSearchFun(value) {
      let val = value
      val = val.replace(/(^\s*)|(\s*$)/g, "").replace(/\s+/g, " ");
      this.fileKeyWord = val;
      if(!val) return

      if(val.length <= 30 ){
        this.httpSearchFile(val, 1);
        this.setFileListSearch([]);
        this.setFileSearchVisible(true);
      }
    },
    // 搜索关键词
    searchChange(event) {
      let value = event.path[0].value;
      // value = value.replace(/(^\s*)|(\s*$)/g, "").replace(/\s+/g, " ");

      if(value.length > 30){
        value = value.substring(0, 30);
        this.$message.warning("搜索关键词最大支持30个字符！");
        return
      }

      this.fileKeyWord = value;
    },
    // 搜索类型选择
    searchTypeChange(event) {
      this.searchType = event.target.value;
      this.httpSearchFile( this.fileKeyWord, 1 );
      this.setFileListSearch([]);
    },
    // 滚动
    resultDomScroll(event){
      // console.log(event, this.$refs.resultDom, this.$refs.resultDom.scrollTop, this.$refs.resultDom.clientHeight, this.$refs.resultDom.scrollHeight, );
      if( (this.$refs.resultDom.scrollTop+this.$refs.resultDom.clientHeight) == this.$refs.resultDom.scrollHeight ){
        this.httpSearchFile(null, 'down');
      }
      else if(this.$refs.resultDom.scrollTop === 0){
        this.httpSearchFile(null, 'up');
      }
    },
    // 搜索接口
    httpSearchFile(keyWord, page) {
      this.fileKeyWord = keyWord?keyWord:this.fileKeyWord;

      switch(page){
        case 'up':
          if(this.page !== 1){
            this.page = this.page - 1;
            return
          }else{
            // this.$message.warn("当前页为第一页！");
            return
          }
          break;
        case 'down':
          if (Math.ceil(this.total/this.size) > this.page ){
            this.page = this.page + 1;
            let array0 = _.cloneDeep(this.fileListSearch);
            array0 = array0.filter( (v,i) => (i >= ( (this.page-1)*this.size ) && i < ( this.page*this.size )) );
            // console.log(this.page, this.size, array0 );
            if(array0.length>0)return
          }
          else{
            this.$message.warn("当前页为最后一页！");
            return
          }
          break;
        default:
          this.page = page;
      };

      this.$message.loading(`正在${this.page===1?'搜索':'加载下一页'}..`, 0);

      // 设置关键词和页码
      this.setSearchKeyWord('');
      this.setSearchKeyNo(1);

      try {
        this.$http(this.$url.searchFile, {
          dirId: this.dirId,
          userId: this.userId,
          keyword: this.fileKeyWord,
          page: this.page,
          size: this.size,
          byName: this.searchType===2?false:true,
          byText: this.searchType===1?false:true,
        })
          .then(res => {

            this.$message.destroy();
            // console.log(res);

            if(res.body.data.length === 0){
              this.$message.warn("文件搜索无匹配结果！");
              this.total = 0;
              this.page = 1;
              return
            }

            this.$message.success(`文件${this.page===1?'搜索':'加载'}成功！`);
            this.total = res.body.total;
            if(this.page===1){
              let array0 = [];
              array0 = res.body.data;
              this.setFileListSearch(array0);
            }else{
              let array0 = _.cloneDeep(this.fileListSearch);
              array0 = _.concat(array0, res.body.data);
              _.uniq(array0);
              // console.log(array0);
              this.setFileListSearch(array0);
            }

          })
          .catch(error => {
            this.$message.destroy();
            this.$message.warn("文件搜索失败！");
          });
      } catch (error) {
        // console.log(error);
      }
    },
    // 文件点击
    fileIdClick(id, filePage) {
      if(this.status === 1){
        return this.$message.warning('文件识别中，无法切换')
      }
      // 设置关键词和页码
      this.setSearchKeyWord(this.fileKeyWord);
      this.setSearchKeyNo(filePage?filePage:1);
      this.setShadowGrayData(null); // 截图临时数据置空
      bus.$emit('identifyResult',null,true) // 关闭截图是被遮罩层

      // this.setFileID(null);
      setTimeout(() => {
        if(id !== this.$store.state.activeFile.id){
          this.setFileID(id);
        }
        else{
          this.setSearchKeyFresh(true);
        }
      }, 300);
    },
    // 阻止冒泡
    eStopPropagation(event) {
      event.stopPropagation();
    },
  },
  watch: {
    fileSearchVisible(newValue) {
      if(!newValue){
        this.setFileListSearch([]);
        this.fileKeyWord = '';
        this.page = 1;
        this.size = 10;
        this.total = 0;
      }
    },
  },
  computed: {
    // 搜索结果
    fileListSearch() {
      let array0 = _.cloneDeep(this.$store.state.file.fileListSearch||[]);
      let array1 = this.searchType===0 ? (array0) : (
            this.searchType===1 ? array0.filter( v => !v.highlightText ) : (
              this.searchType===2 ? array0.filter( v => !v.highlightName ) :
              []
            )
          );
      return array0;
    },
    dirId() {
      return this.$store.state.user.dirId;
    },
    userId() {
      return this.$store.state.user.userId;
    },
    fileSearchVisible() {
      return this.$store.state.status.fileSearchVisible;
    },
    status(){
      return this.$store.state.file.status;
    },
  }
};
</script>

<style lang="less" scoped>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}

.ell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.fileSearch{
  height: 32px;
  width: 388px;
  position: relative;
}

.fileSearch-input{
  height: 32px;
  width: 388px;
  overflow: hidden;
}

.fileSearch-result{
  width: 388px;
  position: absolute;
  background-color: #fff;
  border-left: 1px solid #dcdcdc;
  border-right: 1px solid #dcdcdc;
  border-bottom: 1px solid #dcdcdc;
  z-index: 2;
}

.fileSearch-result-set{
  height: 32px;
  width: 388px;
  padding: 0 6px;
  border-bottom: 1px solid #dcdcdc;
  line-height: 32px;
  font-size: 14px;
  display: flex;
}

.fileSearch-result-set-info{
  width: 120px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  text-align: right;
}

.fileSearch-result-list{
  width: 388px;
  // max-height: 60vh;
  max-height: 400px;
  overflow-x: hidden;
  overflow-y: auto;
}

.fileSearch-result-list-none{
  width: 100%;
  height: 32px;
  line-height: 32px;
  font-size: 12px;
  text-align: center;
}

.fileSearch-result-list-item{
  width: 100%;
  font-size: 14px;
  text-align: left;
  color: #333;
  cursor: pointer;
  &:hover{
    background-color: @primary;
    color: #fff;
  }
}

.fileSearch-result-list-item-name, .fileSearch-result-list-item-text{
  height: 25px;
  line-height: 25px;
}



</style>

<style lang="less">
.fileSearch-result-list-item-span{
  background-color: #EEEE00;
  margin: 0 2px;
  padding: 0 2px;
  color: #333;
}
</style>

